<?php

namespace liketp\model;

use ArrayAccess;
use Countable;
use liketp\Model;

class Collection implements ArrayAccess, Countable
{

    protected $model;
    protected $list = [];

    public function __construct(string $modelName = '')
    {
        $this->model = $modelName;
    }

    public function isEmpty(): bool
    {
        return $this->count() == 0;
    }

    public function toArray(bool $deep = false): array
    {
        if ($deep) {
            $res = [];
            foreach ($this->list as $item) {
                $res[] = $item->toArray($deep);
            }
            return $res;
        } else {
            return $this->list;
        }
    }

    //------------------------------------------------ helper
    public function first()
    {
        return $this->list[0] ?? null;
    }

    public function last()
    {
        $index = $this->count() - 1;
        return $this->list[$index] ?? null;
    }

    public function push(Model $model)
    {
        $this->list[] = $model;
    }

    //------------------------------------------------ ArrayAccess
    public function offsetExists($offset): bool
    {
        return isset($this->list[$offset]);
    }

    public function offsetGet($index)
    {
        return $this->list[$index] ?? null;
    }

    public function offsetSet($offset, $value): void
    {
        $this->list[] = $value;
    }

    public function offsetUnset($offset): void
    {
        unset($this->list[$offset]);
    }


    //------------------------------------------------ Countable
    public function count(): int
    {
        return count($this->list);
    }
}
